﻿using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Easily._02_Form.KimiAI
{
    public class KimiApiService
    {
        private const string BaseUrl = "https://api.moonshot.cn/v1";
        private const string ModelId = "moonshot-v1-8k";
        public string _apiKey { get; set; }
        private ConversationHistory _conversationHistory;

        public KimiApiService(string apiKey)
        {
            _apiKey = apiKey;
            _conversationHistory = new ConversationHistory();
        }

        public void ClearHistory()
        {
            _conversationHistory.ClearHistory();
        }

        public async Task<string> GetResponseAsync(string userMessage)
        {
            // 添加用户消息到对话历史
            _conversationHistory.AddMessage(userMessage);

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");

                // 构建请求体，包括系统消息、用户消息和之前的对话历史
                var messages = new List<object>
            {
                new { role = "system", content = "你是Kimi，由Moonshot AI提供的人工智能助手。" }
            };
                foreach (var message in _conversationHistory.GetRecentMessages())
                {
                    messages.Add(new { role = "user", content = message });
                }
                messages.Add(new { role = "user", content = userMessage }); // 添加当前用户消息

                var requestBody = new
                {
                    model = ModelId,
                    messages = messages.ToArray(),
                    temperature = 0.5 // 可以调整生成内容的随机性
                };

                var jsonContent = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
                var response = await client.PostAsync($"{BaseUrl}/chat/completions", jsonContent);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    var responseObj = JsonConvert.DeserializeObject<KimiResponse>(content);
                    string responseMessage = responseObj.Choices[0].Message.Content;

                    // 添加Kimi的回复到对话历史
                    _conversationHistory.AddMessage(responseMessage);

                    return responseMessage;
                }
                else
                {
                    return $"Error: {response.StatusCode}";
                }
            }
        }
    }
}
